import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProForm, ProFormDateRangePicker, ProFormSelect, ProTable } from '@ant-design/pro-components';
import type { ActionRecordParams } from '@fill/client';
import { rspc } from '@fill/client';
import { Form, Space } from 'antd';
import dayjs from 'dayjs';
import { useRef, useState } from 'react';
import { getFileName } from '../../util';
import { show_in_folder } from '../../util/hack';
import { Export } from './Export';
import { Import } from './Import';

export const actionType = {
  0: {
    text: '导出',
  },
  1: {
    text: '导入',
  },
};

export const actionStatus = {
  0: {
    text: '失败',
  },
  1: {
    text: '成功',
  },
};

const columns: ProColumns<any>[] = [
  {
    title: '序号',
    dataIndex: 'index',
    valueType: 'indexBorder',
    width: 48,
  },
  {
    title: '类型',
    dataIndex: 'types',
    valueEnum: {
      0: {
        text: '导出',
      },
      1: {
        text: '导入',
      },
    },
  },
  {
    title: '操作时间',
    key: 'showTime',
    dataIndex: 'created_at',
    valueType: 'date',
    render(dom, entity) {
      return dayjs(+entity.created_at).format('YYYY-MM-DD HH:mm:ss');
    },
  },
  {
    title: '导入导出内容',
    dataIndex: 'modules',
  },
  {
    title: '状态',
    dataIndex: 'status',
    valueEnum: actionStatus,
  },
  {
    title: '文件',
    dataIndex: 'name',
    render(dom, entity) {
      return getFileName(entity.name);
    },
  },
  {
    title: '操作',
    valueType: 'option',
    key: 'option',
    render: (text, record) => {
      return String(record.types) === '1'
        ? '-'
        : [
        <a
          key="editable"
          onClick={async () => {
            console.log('导入');
            await show_in_folder(record.name);
          }}
        >
          打开文件夹
        </a>,
          ];
    },
  },
];

export default function Record() {
  const actionRef = useRef<ActionType>();
  const [params, setParams] = useState<ActionRecordParams>({
    start: null,
    end: null,
    types: null,
  });

  const { data, isLoading } = rspc.useQuery(['actions.get', {
    arg: params,
  }]);

  const [form] = Form.useForm<any>();
  return (
    <ProTable<any>
      columns={columns}
      actionRef={actionRef}
      editable={{
        type: 'multiple',
      }}
      columnsState={{
        persistenceKey: 'pro-table-singe-demos',
        persistenceType: 'localStorage',
        onChange(value) {
          console.log('value: ', value);
        },
      }}
      dataSource={data}
      rowKey="id"
      search={false}
      options={false}
      form={{
        // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
        syncToUrl: (values, type) => {
          if (type === 'get') {
            return {
              ...values,
              created_at: [values.startTime, values.endTime],
            };
          }
          return values;
        },
      }}
      pagination={{
        pageSize: 20,
        onChange: page => console.log(page),
      }}
      dateFormatter="string"
      loading={isLoading}
      headerTitle={
        <Space>
          <Import />
          <Export module="all" text="导出提报" />
        </Space>
      }
      toolBarRender={() => [
        // eslint-disable-next-line react/jsx-key
        <ProForm<{
          date: string[]
          types: string
        }>
          layout="inline"
          form={form}
          submitter={{
            searchConfig: {
              submitText: '查询',
            },
            // onReset: () => {
            //   setParams({
            //     start: null,
            //     end: null,
            //     type: null,
            //   });
            // },
            render(props, dom) {
              return dom.reverse();
            },
            onSubmit() {
              form.submit();
            },
            onReset() {
              form.resetFields();
              form.submit();
            },
          }}
          onFinish={async (values) => {
            const [start, end] = values?.date || [null, null];

            setParams({
              start: (start && dayjs((`${start} 00:00:00`)).valueOf().toString()) || null,
              end: (end && dayjs((`${end} 23:59:59`)).valueOf().toString()) || null,
              types: values.types || null,
            });
          }}
        >
          <ProFormDateRangePicker name="date" />
          <ProFormSelect name="types" placeholder="请选择类型" valueEnum={actionType} />
        </ProForm>,
      ]}
    />
  );
}
